package com.xihuanjun.util;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: 江溪浣
 * @createDate: 2022/8/10 9:05
 * @description:
 */
public class MapUtils {

    public static Date getDate(Map<String,Object> map , String key) throws ParseException {
        if(map==null){
            return null;
        }
        Object o = map.get(key);
        if(o==null)
            return null;
        String dateString=o.toString();
        String formatString="";
        if(dateString.indexOf(":")==-1){
            formatString="yyyy-MM-dd";
        }else{//有冒号
            if(dateString.indexOf(":")==dateString.lastIndexOf(":")){//1个冒号
                formatString="yyyy-MM-dd HH:mm";
            }else{//2个冒号
                formatString="yyyy-MM-dd HH:mm:ss";
            }
        }
        SimpleDateFormat sdf=new SimpleDateFormat(formatString);
        Date parse = null;
        try {
            parse = sdf.parse(o.toString());
        } catch (ParseException e) {
            throw new ParseException(key+"里的值不符合日期时间格式",0);
        }
        return parse;
    }

    public static Integer getInt(Map<String,Object> map , String key){
        if(map==null){
            return null;
        }
        Object o = map.get(key);
        if(o==null){
            return null;
        }
        return Integer.parseInt(o.toString());
    }

    public static Long getLong(Map<String,Object> map , String key){
        if(map==null){
            return null;
        }
        Object o = map.get(key);
        if(o==null){
            return null;
        }
        return Long.parseLong(o.toString());
    }

    /**
     * 读取字符串
     * @param map
     * @param key
     * @return
     */
    public static  String getString(Map<String,Object> map,String key){
        if(map==null){
            return null;
        }
        Object o = map.get(key);
        if(o==null){
            return null;
        }
        return o.toString();
    }


    public static List<Map<String,Object>> toList(Map map){
        List<Map<String,Object>> list=new ArrayList<>();
        Iterator iterator = map.keySet().iterator();
        while(iterator.hasNext()){
            Object key = iterator.next();
            Object value = map.get(key);
            Map<String,Object> item=new HashMap<>();
            item.put("key",key);
            item.put("value",value);
            list.add(item);
        }
        return list;
    }

    /**
     * 根据value找key
     * @param map
     * @param value
     * @return
     */
    public static Integer getKeyByValue(Map<Integer,String> map,String value){
        Iterator<Integer> iterator = map.keySet().iterator();
        while(iterator.hasNext()){
            Integer key = iterator.next();
            String valueTemp = map.get(key);
            if(valueTemp.equals(value)){
                return key;
            }
        }
        return null;
    }
}
